var map;
var asInitVals = new Array();
var arrMyMarkers = [];
var arrMarkerImgs = [];
var markerCluster;
var housesArr = [];
housesArr[-2] = "blue";
housesArr[-1] = "red";
housesArr[0] = "yellow";
housesArr[1] = "green";
housesArr[2] = "purple";

var ge = null;
var isMouseDown = false;
var lineStringPlacemark = null;
var coords = null;
var pointCount = 0;
var doc = null;

var criteria = {
	search: '',
	rating: '',
	zip: [],
	city: []
}

//google.load("earth", "1");

$(function()
{
	// BEGIN GOOGLE MAPS API V3 CODE
	// set up google map object
    var latlng = new google.maps.LatLng(33.748893,-84.388046);
    var myOptions = {
		zoom: 12,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.HYBRID,
		mapTypeControl: true,
		mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
			position: google.maps.ControlPosition.TOP_RIGHT
		},
		navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.ZOOM_PAN,
			position: google.maps.ControlPosition.TOP_RIGHT
		},
		scaleControl: true,
		scaleControlOptions: {
			position: google.maps.ControlPosition.BOTTOM_RIGHT
		}
    };
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	markerCluster = new MarkerClusterer(map, {maxZoom: 13, gridSize: 40});
	
//	google.earth.createInstance("map_canvas", initCB, failureCB);

	// set up arrMarkerImgs
	for(var i = -2; i < 3; i++)
	{
		var sImg = 'images/monopoly-house-' + housesArr[i] + '24.png';
		arrMarkerImgs[sImg] = new google.maps.MarkerImage(sImg,
			new google.maps.Size(24, 24),
			new google.maps.Point(0,0),
			new google.maps.Point(12, 12)
		);
	}
	
	RefreshData();
	
	$("#properties input#search").keyup(function(){
		setTimeout(SearchTextChanged, 1000);
	});
	
	$("#properties select#rating").change(function(e){
		criteria.rating = $(e.target).val();
		RefreshData();
	});		   
});

function SearchTextChanged()
{
	criteria.search = $("input#search").val();
	if (criteria.search.length == 0){
		$.cookie('search', null);
	}
	else
	{
		$.cookie("search", criteria.search, {expires:365});
	}
	RefreshData();	
}

function RefreshData()
{
	criteria.zip = [];
	criteria.city = [];
	// begin checkbox code
	$.each(['zip', 'city'], function(idx, layertype)
	{
		$("input."+ layertype +"Check:checked").each(function(i, elem)
		{
			criteria[layertype].push($(elem).val());
		});
	});
	$("filter_info").html('');
	if(criteria.zip.length)
		$("#filter_info").html("zips: " + criteria.zip.join(', '));
	if(criteria.city.length)
		$("#filter_info").append(" cities: " + criteria.city.join(', '));
	
	$("#properties div.record").detach();
	//get the data
	$.get('lib/SearchQuery.js.php', {
		QueryID: "properties",
		search: criteria.search,
		rating: criteria.rating,
		zip: criteria.zip.join(','),
		city: criteria.city.join(',')
	 },
	 function(data){
		 $("span#sql").html(data.SQL);
		 $.each(data.Rows, function(i, record)
		 {
			var sOut = '<div class="record ui-widget-content" id="'+ record.id +'">';
    		sOut += '<input id="id" type="hidden" value="'+ record.id +'" />';
    		sOut += '<img id="rating" src="images/monopoly-house-' + housesArr[record.rating] + '24.png" alt=""/>';
			sOut += record.address + ', ' + record.city + ' ' + record.zip + ', ';
			sOut += record.county + ' County - Price: $' + record.price + '</div>';
			$("#properties").append(sOut);
			var sSelector = "#properties div.record:last";
			//deserialize($(sSelector), record);
			$(sSelector).hover(function(e)
			{
				$(e.target).addClass('ui-state-hover');
			},
			function(e){
				$(e.target).removeClass('ui-state-hover');
			}).click(function(e)
			{
				GetPropertyInfo($(e.target).find("input#id").val());
			});
		 });
		 RenderHouseLayer(data.Rows);
	 }, 'json');
	
}

function RenderHouseLayer(data)
{
	for (myMarker in arrMyMarkers)
	{
		arrMyMarkers[myMarker].setMap(null);
	}
	//var arrMarkers = new Array();
	arrMyMarkers = new Array();
	//markerCluster.clearMarkers();
	var arrLatLngs = new Array()

	$.each(data, function(idx, record)
	{
		var myLatlng = new google.maps.LatLng(record.lat,record.lon);
		arrLatLngs.push(myLatlng);
		var marker = new google.maps.Marker({
			position: myLatlng, 
			map: map,
			title: record.id,
			icon: arrMarkerImgs['images/monopoly-house-' + housesArr[record.rating] + '24.png']
	    });
		google.maps.event.addListener(marker, 'click', function(event) {
			var id = $(event.currentTarget).attr('title');
			GetPropertyInfo(id);
		});
		//arrMarkers.push(marker);
		arrMyMarkers[record.id] = marker;

	});
	var bounds = new google.maps.LatLngBounds();
	for ( var i = 0; i < arrLatLngs.length; i++ )
	{
		bounds.extend(arrLatLngs[i]);
	}
	map.fitBounds(bounds);
	//markerCluster.addMarkers(arrMarkers);
}

function in_array (needle, haystack) {

	for (var key in haystack) {
		if (haystack[key] == needle) {
			return haystack[key];
		}
	}
    return null;
}

function SavePropertyAuxInfo()
{
	var rec = {
		mls_id: $("#PropertyWindow #details span#mls_id").text(),
		comments: $("#PropertyWindow textarea#comments").val(),
		rating:$("#PropertyWindow select#rating").val()
	};
	$.get("lib/savePropertyAux.php", rec);
	var sImg = 'images/monopoly-house-' + housesArr[rec.rating] + '24.png' 
	var id = $('#PropertyWindow #details input#id').val();
	arrMyMarkers[id].setOptions({icon: arrMarkerImgs[sImg]});
}

function GetPropertyInfo(id)
{
	$.getJSON("lib/getPropInfo.php", {id:id}, function(data)
	{
		deserialize($("#PropertyWindow"), data);
		// this bit adds the Images (3) to the tab text
		var imgCnt = $("#images_panel img").length;
		if(imgCnt > 0)
		{
			$("#property_tabs").tabs("enable", 1);
			$($("#property_tabs ul li span")[1]).html("Images (" + imgCnt + ")");
		}
		else
		{
			$("#property_tabs").tabs("disable", 1);
			$($("#property_tabs ul li span")[1]).html("Images");
		}
		
		//New! Street view tab
		var panoramaOptions = {
			position: 			arrMyMarkers[id].getPosition(),
			enableCloseButton: 	false,
			visible: true
		};
		var panorama = new google.maps.StreetViewPanorama($("#pano")[0], panoramaOptions);
		map.setStreetView(panorama);
		
		$("#PropertyWindow").dialog({"title": data.address});
		$("#PropertyWindow").dialog( "open" );
		$("#property_tabs").bind('tabsshow', function(event, ui) {
			if (ui.panel.id == "streetviewtab") {
				google.maps.event.trigger(panorama, 'resize');
			}
		});
		$("#zoomTo").click(function()
		{
			map.panTo(arrMyMarkers[id].getPosition());
			map.setZoom(18);
			
		});
	}); // END $.getJSON("getPropInfo.php", {id:id}, function(data)
}

function deserialize(joContainer, data){
	$.each(data, function(key, value){
		//debugger;
		var thing = joContainer.find("#"+key);
		if (thing.length)
		{
			switch(thing[0].nodeName.toLowerCase())
			{
				case 'div':
				case 'span':
				case 'p':
					thing.html(value);
					break;
				case 'a':
					thing.attr('href', value);
					break;
				case 'input':
				case 'textarea':
				case 'select':
					if(key == 'rating' && value == null) value = 0;
					thing.val(value);
					break;
				default:
					break;
			}
		}
		//console.log(key + '=' + value);
	});
}
